const http=require('http');
const fs=require('fs');

let httpServer=http.createServer((req,res)=>{
  // console.log(req.url);
  if(req.url=='/download'){
    let arr=[];
    req.on('data', data=>{
      arr.push(data);
    });
    req.on('end', err=>{
      if(err){
        res.write('error');
        res.end();
      }else{
        let buffer=Buffer.concat(arr);
        let filename=Math.random().toString().replace(/\./g,'')+'.png';



        let buff=new Buffer.from(decodeURIComponent(buffer.toString().replace(/^col=/,'')).replace(/^data:[^,]+;base64,/,''), 'base64');

        res.setHeader('Content-Disposition','attachment; filename=download.png');

        fs.writeFile(`upload/${filename}`, buff, err=>{
          if(err){
            console.log(err);
          }else{
            console.log(`上传成功`);
          }
        });

        res.end(buff);
      }
    });

  }else{
    let rs=fs.createReadStream(`www${req.url}`);
    rs.pipe(res);

    rs.on('error',err=>{
      res.writeHead(404);
      res.write('Not Found');
      res.end();
    });
  }
});

httpServer.listen(8080);
